package api

import (
	"github.com/gin-gonic/gin"
	"server/internal/app/model"
	"server/internal/app/serv"
	"server/internal/pkg/response"
	"strconv"
)

// AreaApi 地区管理
var AreaApi = new(areaApi)

type areaApi struct {
	model.Area
}

// List 列表
func (a areaApi) List(c *gin.Context) {

	response.SuccessList(c, serv.Area.List(0), 0)
}

// Detail 单条
func (a areaApi) Detail(c *gin.Context) {
	id := c.Query("id")

	_, detail := serv.Area.Read(id)

	response.SuccessData(c, detail, "")
}

// Add 添加
func (a areaApi) Add(c *gin.Context) {

	if err := c.ShouldBindJSON(&a); err != nil {
		response.Fail(c, err.Error(), "参数错误")
		return
	}

	if err := serv.Area.Create(a.Area); err.Error == nil {
		response.Success(c, "", "添加成功")
	} else {
		response.Fail(c, err, "添加失败")
	}
}

// Edit 编辑
func (a areaApi) Edit(c *gin.Context) {

	if err := c.ShouldBindJSON(&a); err != nil {
		response.Fail(c, err.Error(), "参数错误")
		return
	}

	if serv.Area.Update(a.Area).Error == nil {
		response.Success(c, "", "编辑成功")
	} else {
		response.Fail(c, "", "编辑失败")
	}
}

// Del 删除
func (a areaApi) Del(c *gin.Context) {
	type Param struct {
		Ids []int `json:"ids"`
	}
	var param Param
	if err := c.ShouldBindJSON(&param); err != nil {
		response.Fail(c, err.Error(), "参数错误")
		return
	}
	if serv.Area.Delete(param.Ids).Error == nil {
		response.Success(c, "", "删除成功")
	} else {
		response.Fail(c, "", "删除失败")
	}
}

// GetSelect 远程下啦
func (a areaApi) GetSelect(c *gin.Context) {
	pid, _ := strconv.Atoi(c.Query("pid"))
	response.Success(c, serv.Area.Select(pid), "")
}

// GetSelectGradually 远程下啦 逐级查看
func (a areaApi) GetSelectGradually(c *gin.Context) {
	pid := c.Query("pid")
	if pid == "" {
		pid = "0"
	}
	pids, _ := strconv.Atoi(pid)
	response.Success(c, serv.Area.GetSelectGradually(pids), "")
}
